import { addAchievTrans } from "@/api/research/achievTrans";
import {
  addPatent,
  delPatent,
  getPatentList,
  upPatent
} from "@/api/research/patent";
import { getUserList } from "@/api/system/user";
import { addDialog } from "@/components/ReDialog";
import {
  dealDataExcept,
  dealDataRide,
  exportData,
  formatDate,
  getTableCol
} from "@/utils/common";
import { message } from "@/utils/message";
import {
  checkStatusRend,
  dataStatusRend,
  rejectDescRend,
  tableFileRend
} from "@/utils/table";
import AddAchievTrans from "@/views/research/achievTrans/form/index.vue";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection, getKeyList } from "@pureadmin/utils";
import dayjs from "dayjs";
import { type Ref, computed, h, onMounted, reactive, ref } from "vue";
import { useRoute } from "vue-router";
import editForm from "../form/index.vue";
import showDetail from "../form/showDetail.vue";

export function useUser(tableRef: Ref) {
  const form = reactive({
    patentName: "",
    patentNumber: "",
    patentType: "",
    status: "",
    examineStatus: "",
    searchDate: [],
    searchDateTwo: [],
    acceptanceDateStartTime: "",
    acceptanceDateEndTime: "",
    authorizeDateStartTime: "",
    authorizeDateEndTime: "",
    projectType: 2,
    orderBy: "desc",
    pageNum: 1,
    pageSize: 10,
    firstInventor: ""
  });
  const finalSearchForm = ref({});
  const formRef = ref();
  const dataList = ref([]);
  const allUserList = ref([]);
  const loading = ref(true);
  const tableCol = ref<any>({});
  const treeData = ref([]);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "专利名称",
      prop: "patentName",
      fixed: "left",
      minWidth: 200
    },
    {
      label: "审核状态",
      prop: "examineStatus",
      minWidth: 90,
      cellRenderer: checkStatusRend
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 80,
      cellRenderer: dataStatusRend
    },
    {
      label: "驳回原因",
      prop: "examineDesc",
      minWidth: 120,
      cellRenderer: rejectDescRend
    },
    {
      label: "专利号",
      prop: "patentNumber",
      minWidth: 100
    },
    {
      label: "专利类型",
      prop: "patentType",
      minWidth: 110
    },
    {
      label: "第一发明人类型",
      prop: "firstInventorType",
      minWidth: 125
    },
    {
      label: "第一发明人",
      prop: "firstInventor",
      minWidth: 110
    },
    {
      label: "专利所属国家",
      prop: "belongCountry",
      minWidth: 110
    },
    {
      label: "专利权人",
      prop: "patentee",
      minWidth: 110
    },
    {
      label: "受理日期",
      prop: "acceptanceDate",
      minWidth: 110,
      formatter: ({ acceptanceDate }) => formatDate(acceptanceDate)
    },
    {
      label: "递交日期",
      prop: "sendDate",
      minWidth: 110,
      formatter: ({ sendDate }) => formatDate(sendDate)
    },

    {
      label: "授权日期",
      prop: "authorizeDate",
      minWidth: 100,
      formatter: ({ authorizeDate }) => formatDate(authorizeDate)
    },
    //  ===
    {
      label: "授权附件",
      prop: "authorizeFiles",
      minWidth: 100,
      cellRenderer: ({ row }) => tableFileRend(row, "authorizeFiles")
    },
    {
      label: "奖项名称",
      prop: "rewardName",
      minWidth: 100
    },
    {
      label: "奖项级别",
      prop: "rewardLevel",
      minWidth: 100
    },
    {
      label: "获奖日期",
      prop: "obtainDate",
      minWidth: 100,
      formatter: ({ obtainDate }) => formatDate(obtainDate)
    },
    {
      label: "获奖附件",
      prop: "obtainDateFiles",
      minWidth: 100,
      cellRenderer: ({ row }) => tableFileRend(row, "obtainDateFiles")
    },
    {
      label: "转化金额(万元)",
      prop: "transformPrice",
      minWidth: 120,
      formatter: ({ transformPrice }) => dealDataExcept(transformPrice)
    },
    {
      label: "转化附件",
      prop: "transformFiles",
      minWidth: 100,
      cellRenderer: ({ row }) => tableFileRend(row, "transformFiles")
    },
    {
      label: "关联人员",
      prop: "userList",
      minWidth: 160,
      formatter: ({ userList }) => userList.map(v => v.name).join(",")
    },
    {
      label: "获得积分",
      prop: "score",
      minWidth: 100
    },
    {
      label: "创建人",
      prop: "createUserName",
      minWidth: 100
    },
    {
      label: "创建时间",
      prop: "gmtCreate",
      minWidth: 140,
      formatter: ({ gmtCreate }) => dayjs(gmtCreate).format("YYYY-MM-DD HH:mm")
    },
    {
      label: "修改时间",
      prop: "gmtModified",
      minWidth: 140,
      formatter: ({ gmtModified }) =>
        dayjs(gmtModified).format("YYYY-MM-DD HH:mm")
    },
    {
      label: "操作",
      prop: "operation",
      fixed: "right",
      align: "left",
      width: 270,
      slot: "operation"
    }
  ];

  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  const handleDelete = async row => {
    await delPatent(row.id);
    message("删除成功", { type: "success" });
    onSearch();
  };

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    form.pageNum = val;
    onSearch();
  }

  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    message(`已删除用户编号为 ${getKeyList(curSelected, "id")} 的数据`, {
      type: "success"
    });
    tableRef.value.getTableRef().clearSelection();
    onSearch();
  }

  const loadAllUser = async () => {
    let params = {
      pageNum: 1,
      pageSize: 500
    };
    let { data } = await getUserList(params);
    allUserList.value = data.records || [];
  };

  async function onSearch() {
    loading.value = true;
    let tempForm = { ...form };
    if (tempForm.searchDate && tempForm.searchDate.length > 0) {
      tempForm.acceptanceDateStartTime = tempForm.searchDate[0] + " 00:00:00";
      tempForm.acceptanceDateEndTime = tempForm.searchDate[1] + " 23:59:59";
    }
    if (tempForm.searchDateTwo && tempForm.searchDateTwo.length > 0) {
      tempForm.authorizeDateStartTime = tempForm.searchDateTwo[0] + " 00:00:00";
      tempForm.authorizeDateEndTime = tempForm.searchDateTwo[1] + " 23:59:59";
    }
    delete tempForm.searchDate;
    delete tempForm.searchDateTwo;
    finalSearchForm.value = tempForm;
    const { data } = await getPatentList(tempForm);
    dataList.value = data.records || [];
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.pageNum;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    form.searchDate = [];
    form.searchDateTwo = [];
    onSearch();
  };

  // 导出数据
  const exportModuleData = () => {
    exportData("专利", "/patent/export", finalSearchForm.value);
  };

  function openDetail(title = "新增", row?) {
    addDialog({
      title: "查看专利",
      props: {
        formInline: {
          id: row?.id ?? undefined,
          createUserId: row?.createUserId ?? undefined,
          title,
          patentName: row?.patentName ?? "",
          patentNumber: row?.patentNumber ?? "",
          acceptanceDate: row?.acceptanceDate ?? "",
          acceptanceFiles: row?.acceptanceFiles ?? "",
          authorizeDate: row?.authorizeDate ?? "",
          authorizeFiles: row?.authorizeFiles ?? "",
          firstInventor: row?.firstInventor ?? "",
          firstInventorType: row?.firstInventorType ?? "",
          issueDate: row?.issueDate ?? "",
          issueFiles: row?.issueFiles ?? "",
          obtainDate: row?.obtainDate ?? "",
          obtainDateFiles: row?.obtainDateFiles ?? "",
          patentType: row?.patentType ?? "",
          rewardLevel: row?.rewardLevel ?? "",
          rewardName: row?.rewardName ?? "",
          secondInventor: row?.secondInventor ?? "",
          secondInventorType: row?.secondInventorType ?? "",
          showTwoInventor: row?.secondInventor ? true : false,
          transformFiles: row?.transformFiles ?? "",
          obtainReward: row?.obtainReward ?? 0,
          transform: row?.transform ?? 0,
          transformPrice: dealDataExcept(row?.transformPrice) ?? null,
          score: row?.score ?? null,
          examineStatus: row?.examineStatus ?? 0,
          examineDesc: row?.examineDesc ?? "",
          sendDate: row?.sendDate ?? null,
          belongCountry: row?.belongCountry ?? null,
          patentee: row?.patentee ?? null
        },
        userList: row?.userList || []
      },
      width: "1000px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(showDetail),
      beforeSure: done => {
        done();
      }
    });
  }

  function openDialog(title = "新增", row?) {
    let userIds = [];
    if (row?.userList) {
      userIds = row.userList.map(v => v.id);
    }
    let patenteeList = [
      {
        patentee: ""
      }
    ];
    if (row?.patentee) {
      patenteeList = row.patentee.split(",").map(v => {
        return { patentee: v };
      });
    }
    addDialog({
      title: `${title}专利`,
      props: {
        formInline: {
          id: row?.id ?? undefined,
          title,
          patentName: row?.patentName ?? "",
          patentNumber: row?.patentNumber ?? "",
          acceptanceDate: formatDate(row?.acceptanceDate, ""),
          acceptanceFiles: row?.acceptanceFiles ?? "",
          authorizeDate: formatDate(row?.authorizeDate, ""),
          authorizeFiles: row?.authorizeFiles ?? "",
          firstInventor: row?.firstInventor ?? "",
          firstInventorType: row?.firstInventorType ?? "",
          issueDate: formatDate(row?.issueDate, ""),
          issueFiles: row?.issueFiles ?? "",
          obtainDate: formatDate(row?.obtainDate, ""),
          obtainDateFiles: row?.obtainDateFiles ?? "",
          patentType: row?.patentType ?? "",
          rewardLevel: row?.rewardLevel ?? "",
          rewardName: row?.rewardName ?? "",
          secondInventor: row?.secondInventor ?? "",
          secondInventorType: row?.secondInventorType ?? "",
          showTwoInventor: row?.secondInventor ? true : false,
          transformFiles: row?.transformFiles ?? "",
          obtainReward: row?.obtainReward ?? 0,
          transform: row?.transform ?? 0,
          transformPrice: dealDataExcept(row?.transformPrice) ?? null,
          userIds: userIds,
          score: row?.score ?? null,
          sendDate: row?.sendDate ?? null,
          belongCountry: row?.belongCountry ?? null,
          patenteeList: patenteeList
        },
        userList: allUserList
      },
      width: "1000px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;
        function chores() {
          message("操作成功", { type: "success" });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            let newForm = { ...curData };
            newForm.score = newForm.score || 0;
            newForm.transformPrice = dealDataRide(newForm.transformPrice);
            if (newForm.patenteeList && newForm.patenteeList.length > 0) {
              newForm.patentee = newForm.patenteeList
                .filter(v => v.patentee)
                .map(v => v.patentee)
                .join(",");
            }
            delete newForm.patenteeList;
            console.log("newForm ", newForm);
            // 表单规则校验通过
            if (title === "新增") {
              await addPatent(newForm);
              chores();
            } else {
              await upPatent(newForm);
              chores();
            }
          }
        });
      }
    });
  }

  const achievFormRef = ref();
  function doAchievTrans(row?) {
    let patenteeList = [
      {
        patentee: ""
      }
    ];
    if (row?.patentee) {
      patenteeList = row.patentee.split(",").map(v => {
        return { patentee: v };
      });
    }
    addDialog({
      title: "新增成果转化",
      props: {
        formInline: {
          id: undefined,
          acquisitionCompany: row?.acquisitionCompany ?? "",
          acquisitionFiles: row?.acquisitionFiles ?? "",
          acquisitionPrice: dealDataExcept(row?.acquisitionPrice) ?? "",
          firstInventor: row?.firstInventor ?? "",
          firstInventorType: row?.firstInventorType ?? "",
          outId: row?.id ?? undefined,
          patentName: row?.patentName ?? "",
          patentType: row?.patentType ?? "",
          patentee: row?.patentee ?? "",
          secondInventor: row?.secondInventor ?? "",
          secondInventorType: row?.secondInventorType ?? "",
          score: null,
          patenteeList: patenteeList
        }
      },
      width: "800px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(AddAchievTrans, { ref: achievFormRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = achievFormRef.value.getRef();
        const curData = options.props.formInline;
        function chores() {
          message("新增成果转化成功", { type: "success" });
          done(); // 关闭弹框
        }
        FormRef.validate(async valid => {
          if (valid) {
            let formVal = { ...curData };
            formVal.score = formVal.score || 0;
            formVal.acquisitionPrice = dealDataRide(formVal.acquisitionPrice);
            if (formVal.patenteeList && formVal.patenteeList.length > 0) {
              formVal.patentee = formVal.patenteeList
                .filter(v => v.patentee)
                .map(v => v.patentee)
                .join(",");
            }
            delete formVal.patenteeList;
            console.log("formVal ", formVal);
            // 表单规则校验通过
            await addAchievTrans(formVal);
            chores();
          }
        });
      }
    });
  }

  onMounted(async () => {
    const { query } = useRoute();
    if (query.examineStatus) {
      form.examineStatus = Number(query.examineStatus) as any;
    }
    if (query.status) {
      form.status = Number(query.status) as any;
    }
    tableCol.value = await getTableCol("patent");

    onSearch();

    // 获取所有用户
    loadAllUser();
  });

  return {
    form,
    tableCol,
    loading,
    columns,
    dataList,
    treeData,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    doAchievTrans,
    openDetail,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    exportModuleData
  };
}
